package transactions.service.nosecure;

import java.io.*;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import dinamica.*;
import dinamica.xml.Document;
import dinamica.xml.Element;

/**
 * Recorre el directorio configurado en el web.xml, para obtener la lista
 * de los contexto asociados al contenedor, a su vez obtiene los web.xml
 * de cada contexto los parsea para obtener los valores del datasource y alias, 
 * donde el datasource tiene que ser igual al datasource de la aplicacion de seguridad
 * (Solo se obtendra aquellas aplicaciones que posean el mismo datasource).
 * Fecha de creacion: 2008-08-02<br>
 * Fecha de actualizacion: 2008-08-07<br>
 * (c) 2008 Martin Cordova y Asociados C.A<br>
 * http://www.martincordova.com<br>
 * @author Francisco Galizia (galiziafrancisco@gmail.com)
 */
public class GetAplication extends GenericTransaction implements EntityResolver
{

	 @Override
     public InputSource resolveEntity(String arg0, String arg1)
                     throws SAXException, IOException {
             InputSource s =  new InputSource(getClass().getResourceAsStream("/javax/servlet/resources/web-app_2_3.dtd"));
             s.setPublicId(arg0);
             s.setSystemId("javax.servlet.resources.web-app_2_3.dtd");
             return s;
     }
	 
	/* (non-Javadoc)
	 * @see dinamica.GenericTransaction#service(dinamica.Recordset)
	 */
	@Override
	public int service(Recordset inputParams) throws Throwable
	{
		//reutilizar la logica del padre
		super.service(inputParams);
		
		if(getContext().getInitParameter("base-dir") == null || getContext().getInitParameter("base-dir").equals(""))
			throw new Throwable("Parameter [base-dir] not found in the web.xml");
		
		//datasource from application security
		String dataSourceAdmin = getContext().getInitParameter("def-datasource");
		
		//recordset that contains the path name and aliases 
		//Applications of the containeror
		Recordset rs = new Recordset();
		rs.append("path-app", java.sql.Types.VARCHAR);
		rs.append("name-app", java.sql.Types.VARCHAR);
		rs.append("alias-app", java.sql.Types.VARCHAR);
		
		//get the file with the path set in the web.xm
		File fsource = new File(getContext().getInitParameter("base-dir"));
		
		//if there is not throwing an exception
		if (!fsource.exists())
			throw new Throwable("Invalid directory: " + getContext().getInitParameter("base-dir"));
		
		//get the list of directories
		String items[] = fsource.list();
		
		//traverse each file and get the route of context
		for (int i=0;i<items.length;i++)
		{
			//contains the full path of the application or context
			String pathApp = fsource.getPath() + File.separator + items[i] + File.separator + "WEB-INF" + File.separator + "action";
			
			//contains the full path of the web.xml of application or context
			String pathAppWebXML = fsource.getPath() + File.separator + items[i] + File.separator + "WEB-INF" + File.separator + "web.xml";
			
			//Application Name
			String nameApp = items[i];
			
			//web.xml obtain the application
			FileInputStream  webXML = new FileInputStream(pathAppWebXML);
			
			//obtaining the document
			Document doc = new Document(webXML,this);
			
			//Obtain the array of elements param-value of the web.xml
			Element initParams[] = doc.getElements("filter[filter-name = 'SecurityFilter']/init-param/param-value");
						
			//if the array does not mean that the element 
			//filter security and commented that it 
			//So it is discarded
			if(initParams.length > 0){
				
				//get the number 1 position in the array as this
				//Is the one containing the name of the datasource
				Element paramValueDS = initParams[1];
	
				//value of the element param-value corresponds to the datasource
				//From the application of security
				if(paramValueDS.getValue().equals(dataSourceAdmin)){
					
					//get the value of the position of number 0 
					//array which corresponds with the nickname of the
					//application
					Element paramValueAlias = initParams[0];
					
					//add a new record to recordset
					rs.addNew();
					rs.setValue("path-app", pathApp);
					rs.setValue("name-app", nameApp);
					rs.setValue("alias-app", paramValueAlias.getString());
				}		
			}
		}
		
		//publish the recordset
		publish("aplicaciones", rs);
		
		return 0;
	}
}
